﻿using CCLog;
using CommonEntity.CommonImageEntities;
using CommonEntity.Handlers;
using ScienceAppService.ModuleInterface;
using ScienceAppService.RpcUtils;
using ScienceRpcServe.Protos;

namespace ScienceAppService.ModuleService;
public class SplitService : ISplitService
{

    #region private
    private DicomSplit.DicomSplitClient _rpcClient;

    private ILoggerService _logger;
    #endregion

    public event CommonHandler<string>? AlarmEvent;

    public event CommonHandler<bool> ChooseSeriesEvent;


    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger"></param>
    public SplitService(ILoggerService logger)
    {
        _rpcClient = RpcConfigure.Instance.GetDicomSplitClient();
        _logger = logger;
    }

    /// <summary>
    /// 序列选中加载
    /// </summary>
    /// <param name="seriesKey"></param>
    /// <returns></returns>
    public async Task<bool> ChooseSeries(string seriesKey)
    {
        try
        {
            var rs = await _rpcClient.ChooseSeriesAsync(new StringRequest() { Value = seriesKey });
            if (!string.IsNullOrEmpty(rs.Remark))
            {
                AlarmEvent?.Invoke(rs.Remark);
            }
            ChooseSeriesEvent?.Invoke(true);
            return rs.IsSuccess;
        }
        catch (Exception e)
        {
            _logger.Error(nameof(ChooseSeries), e.Message);
            return false;
        }
    }

    /// <summary>
    /// Dicom序列划分
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<IList<SplitSeriesInfo>?> SplitDicom(string? dir)
    {
        try
        {
            if(!Directory.Exists(dir)) return null;
            var rs = await _rpcClient.SplitDicomsByDirAsync(new StringRequest(){Value = dir});
            if (!string.IsNullOrEmpty(rs.Remark))
            {
                AlarmEvent?.Invoke(rs.Remark);
            }
            return rs.ToSplitSeriesInfoList();
        }
        catch (Exception e)
        {
            _logger.Error(nameof(SplitDicom), e.Message);
            return null;
        }
    }
}
